package com.cloudcentral.config;

import com.alibaba.fastjson.JSON;
import com.cloudcentral.util.Result;
import lombok.NonNull;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.cloudcentral.util.Utils.errorMessage;

/**
 * Create by Administrator
 * 2023/10/16 15:40
 */
@Configuration
public class GlobalErrorWebExceptionHandler implements ErrorWebExceptionHandler {
  @NonNull
  @Override
  public Mono<Void> handle(@NonNull ServerWebExchange exchange, @NonNull Throwable throwable) {
    ServerHttpResponse response = exchange.getResponse();
    // 设置返回JSON
    List<Charset> charsets = new ArrayList<>();
    charsets.add(StandardCharsets.UTF_8);
    response.getHeaders().setAcceptCharset(charsets);
    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    if (response.isCommitted()) return Mono.error(throwable);
    else {
      String json = JSON.toJSONString(Result.notfound(errorMessage(throwable)));
      DataBuffer dataBuffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
      return response.writeWith(Mono.just(dataBuffer));
    }
  }
}
